<template>
    <div style="width: 100%; height: 100%">
        <div class="editorToolHeader">
            <!-- <a-button type="primary" style="margin-right: 10px" @click="getHtml"
                >获取 html</a-button
            > -->
            <a-button type="primary" style="margin-right: 10px" @click="getSsml"
                >获取ssml</a-button
            >
            <a-button
                type="primary"
                style="margin-right: 10px"
                @click="handleSelectionChange"
                >试听</a-button
            >
            <!-- <a-button
                type="primary"
                style="margin-right: 10px"
                @click="handleThrottleClick($event, 9999)"
                >节流</a-button
            > -->
            <muteMenu ref="muteMenuRef" :editor="editorRef"></muteMenu>
            <continuousMenu
                ref="continuousRef"
                :editor="editorRef"
            ></continuousMenu>
            <digitalMenu ref="sayAsRef" :editor="editorRef"></digitalMenu>
            <characterMenu
                ref="characterRef"
                :editor="editorRef"
            ></characterMenu>
            <pinyinMenu ref="pinyinRef" :editor="editorRef"></pinyinMenu>
            <!-- <markPhoneMenu
                ref="markPhoneRef"
                :editor="editorRef"
            ></markPhoneMenu> -->

            <pinyinBacthMenu :editor="editorRef"> </pinyinBacthMenu>

            <continuousBatchMenu
                ref="continuousBatchRef"
                :editor="editorRef"
            ></continuousBatchMenu>
        </div>
        <div class="editorMainContent">
            <pinyinPopover :editor="editorRef"></pinyinPopover>
            <!-- 工具栏 -->
            <!-- <Toolbar
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            style="border-bottom: 1px solid #ccc"
        /> -->
            <!-- 编辑器 -->
            <Editor
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                @onChange="handleChange"
                @onCreated="handleCreated"
                @onDestroyed="handleDestroyed"
                @onFocus="handleFocus"
                @onBlur="handleBlur"
                @customAlert="customAlert"
                style="height: 100%"
                mode="simple"
            />
        </div>
    </div>
</template>

<script setup>
// import { h } from 'snabbdom'
import { onBeforeUnmount, ref, shallowRef, watch } from "vue";
// import { IButtonMenu } from '@wangeditor/core'
import { Boot } from "@wangeditor/editor";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import {
    serializeToSSML,
    serializeToSSMLBySelect,
} from "./utils/serialize-microsoft.js";
import muteMenu from "./menuComponents/muteMenu/mute-menu.vue";
import pinyinMenu from "./menuComponents/pinyinMenu/pinyin-menu.vue";
import digitalMenu from "./menuComponents/digitalMenu/digital-menu.vue";
import characterMenu from "./menuComponents/characterMenu/character-menu.vue";
import continuousMenu from "./menuComponents/continuousMenu/continuous-menu.vue";
import continuousBatchMenu from "./menuComponents/continuousBatchMenu/continuous-batch-menu.vue";
import markPhoneMenu from "./menuComponents/markPhoneMenu/markPhone-menu.vue";
import pinyinBacthMenu from "./menuComponents/pinyinBacthMenu/pinyinBacth-menu.vue";
import pinyinPopover from "./menuComponents/pinyinMenu/pinyinPopover.vue";

import markPhoneComponent from "./coreComponents/markPhoneComponent/index";
import breakComponent from "./coreComponents/breakComponent/index";
import phonemeComponent from "./coreComponents/phonemeComponent/index";
import sayAsComponent from "./coreComponents/sayAsComponent/index";
import paragraphComponent from "./coreComponents/paragraphComponent/index";
import prosodyComponent from "./coreComponents/prosodyComponent/index";
import throttle from "lodash.throttle";
import { message } from "ant-design-vue";

const emit = defineEmits({ created: null });

Boot.registerModule(breakComponent);
Boot.registerModule(phonemeComponent);
Boot.registerModule(sayAsComponent);
Boot.registerModule(paragraphComponent);
Boot.registerModule(prosodyComponent);
Boot.registerModule(markPhoneComponent);

const props = defineProps({
    disable: {
        type: Boolean,
        default: false,
    },
});

const muteMenuRef = ref();
const pinyinRef = ref();
const sayAsRef = ref();
const continuousRef = ref();
const characterRef = ref();
const continuousBatchRef = ref();
// 编辑器实例，必须用 shallowRef ，重要！
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");

// 编辑器配置
const editorConfig = {
    placeholder: "请输入内容...",
    MENU_CONF: {
        insertImage: {
            checkImage(src) {
                console.log("image src", src);
                if (src.indexOf("http") !== 0) {
                    return "图片网址必须以 http/https 开头";
                }
                return true;
            },
        },
    },
};

// 工具栏配置
const toolbarConfig = {
    // toolbarKeys: ['headerSelect', 'bold', 'my-menu-1'],
    // excludeKeys: [],
    // insertKeys: {
    //     index: 0,
    //     keys: "my-menu-1",
    // },
};

// 编辑器回调函数
const handleCreated = (editor) => {
    console.log("created", editor);
    editorRef.value = editor; // 记录 editor 实例，重要！
    muteMenuRef.value.onOpen(editor);
    pinyinRef.value.onOpen(editor);
    sayAsRef.value.onOpen(editor);
    continuousRef.value.onOpen(editor);
    characterRef.value.onOpen(editor);
    continuousBatchRef.value.onOpen(editor);
    setEditorStatus();
    emit("created");
    console.log(editor.getConfig());
    // valueHtml.value =
    // editor.setHtml('<p>hello&nbsp;world999999</p>')
    // window.editor = editor // 临时测试使用，用完删除
};
const handleChange = (editor) => {
    var text = editor.getText();
    if (!text) {
        valueHtml.value = "";
    }
};
const handleDestroyed = (editor) => {
    // console.log('destroyed', editor)
};
const handleFocus = (editor) => {
    // console.log('focus', editor)
};
const handleBlur = (editor) => {
    // console.log('blur', editor)
};
const customAlert = (info, type) => {
    alert(`【自定义提示】${type} - ${info}`);
};

// const customPaste = (editor, event, callback) => {
//     console.log("ClipboardEvent 粘贴事件对象", event);

//     // 自定义插入内容
//     editor.insertText("xxx");

//     // 返回值（注意，vue 事件的返回值，不能用 return）
//     callback(false); // 返回 false ，阻止默认粘贴行为
//     // callback(true) // 返回 true ，继续默认的粘贴行为
// };

// 及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;

    // 销毁，并移除 editor
    editor.destroy();
});
const editorUid = ref("uid");
const getHtml = () => {
    const editor = editorRef.value;
    if (editor == null) return null;
    // console.log(editor.getHtml());
    var html = editor.getHtml();
    console.log("html:", html);
    return {
        html: html,
        uid: editorUid.value,
    };
};

const setHtml = (html, uid) => {
    valueHtml.value = html;
    editorUid.value = uid || "uid";
};

const getSsml = () => {
    const editor = editorRef.value;
    if (editor == null) return null;
    var ssml = serializeToSSML(editorRef.value);
    console.log("ssml:", ssml);
    return {
        ssml: ssml,
        uid: editorUid.value,
    };
};

const getText = () => {
    const editor = editorRef.value;
    if (editor == null) return null;
    var text = editorRef.value.getText();
    return {
        text: text,
        uid: editorUid.value,
    };
};

const setEditorStatus = () => {
    if (editorRef.value && editorRef.value.enable) {
        if (props.disable) {
            editorRef.value?.disable();
        } else {
            editorRef.value?.enable();
        }
    }
};

/**
 * 节流·足球
 */
const handleThrottleClick = (evt, result) => {
    return throttle((evt) => {
        // ---- ^ 业务逻辑 ----
        // 定义fn方法
        const fn = (evt) => {
            console.log("throttle =>", evt, result);
        };
        // 调用fn方法
        fn(evt);
        // ---- / 业务逻辑 ----
    });
};

const handleSelectionChange = () => {
    var textStr = editorRef.value?.getSelectionText();
    if (textStr) {
        if (textStr.length < 30) {
            const selection = editorRef.value?.getFragment();
            const ssml = serializeToSSMLBySelect(editorRef.value, selection);
            console.log("select ssml", selection, ssml);
        } else {
            console.log("试听内容不能超过30个字符");
            message.warn("试听内容不能超过30个字符");
        }
    }else{
        message.warn("请选择试听内容");
    }

    // const range = selection.getRangeAt(0);
    // const commonAncestor = range.commonAncestorContainer;
    // console.log(selection, range, commonAncestor);
    // if (commonAncestor.nodeType === Node.ELEMENT_NODE) {
    //     const childNodes = commonAncestor.childNodes;
    //     const selectedNodes = [];

    //     for (let i = 0; i < childNodes.length; i++) {
    //         if (range.intersectsNode(childNodes[i])) {
    //             selectedNodes.push(childNodes[i]);
    //         }
    //     }

    //     console.log(selectedNodes);
    // }
};

watch(
    () => props.disable,
    (val) => {
        console.log("disable", props.disable);
        setEditorStatus();
    },
    { immediate: true, deep: true }
);

defineExpose({
    setHtml,
    getHtml,
    getSsml,
    getText,
});
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style src="./css/iconfont.css"></style>
<style>
/* .w-e-text-placeholder{
        line-height: 1.5rem;
    } */
.w-e-text-container [data-slate-editor] span {
    /* line-height: 2.6rem; */
}

.editorToolHeader {
    height: 40px;
    width: 100%;
    display: flex;
    position: relative;
}
.editorMainContent {
    width: 100%;
    height: calc(100% - 50px);
    border: 1px solid #ccc;
    position: relative;
    /* line-height: 2.6rem; */
}

.w-e-scroll::-webkit-scrollbar-track-piece {
    background-color: #ededed;
    cursor: pointer;
    border-radius: 25px;
}
/*定义滚动条整体的样式*/
.w-e-scroll::-webkit-scrollbar-track-piece {
    background-color: #ededed;
    cursor: pointer;
    border-radius: 25px;
}

/*滚动条的样式*/
.w-e-scroll::-webkit-scrollbar-thumb {
    background-color: #aaa;
    border: none;
    border-radius: 25px !important;
    height: 12px !important;
}

.w-e-scroll::-webkit-scrollbar {
    height: 8px !important;
    width: 4px !important;
}

.ssml-wrapper {
    --ssml-voice: #2ecc71;
    --ssml-audio: #3498db;
    --ssml-emphasis: #f39c12;
    --ssml-phoneme: #9b59b6;
    --ssml-prosody: #e74c3c;
    --ssml-say-as: #1abc9c;
    --ssml-sub: #e67e22;
    --ssml-p: #d35400;
    --ssml-s: #c0392b;
    --ssml-w: #16a085;
    --ssml-break: #27ae60;
    --ssml-mstts--express-as: #ffff00;
    --custom-management: #ff1493;
    --moyin-w: #c0392b;

    position: relative;
    box-sizing: border-box;
    border: 0px;
    /* line-height: 2.6rem; */
    vertical-align: center;
}

.ssmlContentWrapper {
    border-radius: 3px;
}
.ssmlContentWrapper::before {
    content: attr(data-content);
}

.remarkWrapper {
    /* position: absolute;
    top: -21px;
    left: 0px; */

    display: inline-flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;

    padding: 0 4px;
    margin: 0 0 0 4px;

    line-height: normal;
    font-size: 0.65rem;
    border-radius: 3px;

    color: white;
    height: 18px;
    max-width: 200px;
    white-space: nowrap;
    transition: all 0.1s ease;
    background-color: #0f0;

    user-select: none;
}

.remarkWrapper:hover {
    z-index: 1;
    max-width: 300px;
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.5);
}

.data-content {
    display: inline-block;
    text-overflow: ellipsis;
    overflow: hidden;
}
.data-content::before {
    content: attr(data-content);
}

/* .iconfont {
    color: #e2fafa;
    opacity: 0.6;
    font-size: 0.65rem;
    transition: all 0.1s ease;
} */
</style>
